<template>
  <div class="comment-tree">
    <!-- 评论发表区域 -->
    <div class="comment-form-section">
      <CommentForm :blog-id="blogId" @comment-submitted="handleCommentSubmitted" />
    </div>

    <!-- 评论统计 -->
    <div v-if="stats" class="comment-stats">
      <span class="stats-item">
        <el-icon>
          <ChatDotRound />
        </el-icon>
        共 {{ stats.totalComments }} 条评论
      </span>
      <span class="stats-item">
        <el-icon>
          <User />
        </el-icon>
        {{ stats.topLevelComments }} 条主评论
      </span>
    </div>

    <!-- 评论列表 -->
    <div v-loading="loading" class="comment-list">
      <div v-if="comments.length === 0" class="no-comments">
        <el-empty description="暂无评论，快来发表第一条评论吧！" />
      </div>

      <div v-else>
        <CommentItem
          v-for="comment in comments"
          :key="comment.id"
          :comment="comment"
          :blog-id="blogId"
          :active-reply-id="activeReplyId"
          @reply="handleReply"
          @like="handleLike"
          @show-reply="handleShowReply"
          @load-more-replies="loadMoreReplies"
        />
      </div>

      <!-- 加载更多 -->
      <div v-if="hasMore" class="load-more">
        <el-button :loading="loadingMore" size="large" @click="loadMoreComments">
          加载更多评论
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { ChatDotRound, User } from '@element-plus/icons-vue'
  import { getCommentTree, likeComment, getCommentStats, loadMoreChildren } from '@/api/comment'
  import type { Comment, CommentStats, CommentLikeParam } from '@/types/comment'
  import CommentForm from './CommentForm.vue'
  import CommentItem from './CommentItem.vue'

  const props = defineProps<{
    blogId: string
  }>()

  const comments = ref<Comment[]>([])
  const stats = ref<CommentStats | null>(null)
  const loading = ref(false)
  const loadingMore = ref(false)
  const hasMore = ref(false)
  const currentPage = ref(1)
  const pageSize = 10
  const activeReplyId = ref<string | null>(null)

  const loadComments = async (page = 1) => {
    if (page === 1) {
      loading.value = true
    } else {
      loadingMore.value = true
    }

    try {
      const data = await getCommentTree({
        blogId: props.blogId,
        pageNum: page,
        pageSize,
        childrenLimit: 5, // 限制每个主评论的回复数量
      })

      if (page === 1) {
        comments.value = data.records || []
      } else {
        comments.value.push(...(data.records || []))
      }

      hasMore.value = page < (data.pages || 1)
      currentPage.value = page
    } catch (error) {
      console.error('加载评论失败:', error)
      ElMessage.error('加载评论失败，请稍后重试')
    } finally {
      loading.value = false
      loadingMore.value = false
    }
  }

  const loadMoreComments = () => {
    loadComments(currentPage.value + 1)
  }

  // 加载更多回复
  const loadMoreReplies = async (parentId: string, offset: number) => {
    try {
      const data = await loadMoreChildren({
        parentId,
        offset,
        limit: 5, // 每次加载5条回复
      })

      // 找到对应的主评论并更新回复列表
      const parentComment = comments.value.find(comment => comment.id === parentId)
      if (parentComment && parentComment.children) {
        parentComment.children.push(...data)

        // 更新是否还有更多回复的状态
        parentComment.hasMore = data.length >= 5
      }
    } catch (error) {
      console.error('加载更多回复失败:', error)
      ElMessage.error('加载更多回复失败，请稍后重试')
    }
  }

  const handleCommentSubmitted = () => {
    //不需要刷新，因为评论需要审核通过才能展示，没有必要刷新
    /* loadComments(1)
    loadStats() */
  }

  const handleReply = () => {
    // 刷新评论列表
    loadComments(1)
    loadStats()
    // 关闭回复框
    activeReplyId.value = null
  }

  // 控制回复框显示
  const handleShowReply = (commentId: string | null) => {
    activeReplyId.value = commentId
  }

  const handleLike = async (comment: Comment) => {
    try {
      const param: CommentLikeParam = {
        commentId: comment.id,
        isLike: !comment.isLiked,
      }

      await likeComment(param)

      // 更新本地状态
      comment.isLiked = !comment.isLiked
      comment.likeCount += comment.isLiked ? 1 : -1

      ElMessage.success(comment.isLiked ? '点赞成功' : '取消点赞成功')
    } catch (error) {
      console.error('点赞操作失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  }

  const loadStats = async () => {
    try {
      stats.value = await getCommentStats(props.blogId)
    } catch (error) {
      console.error('加载评论统计失败:', error)
    }
  }

  onMounted(() => {
    loadComments()
    loadStats()
  })
</script>

<style scoped>
  .comment-tree {
    max-width: 100%;
    margin: 0;
  }

  .comment-form-section {
    margin-bottom: 24px;
    padding: 24px;
    background: var(--bg-color, #ffffff);
    border-radius: 12px;
    border: 1px solid var(--border-color, #e4e7ed);
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  }

  .comment-stats {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    padding: 12px 20px;
    border-radius: 10px;
    border: 1px solid var(--border-color, #e4e7ed);
    font-size: 14px;
    color: var(--text-secondary, #666);
  }

  .stats-item {
    display: flex;
    align-items: center;
    gap: 6px;
    font-weight: 500;
  }

  .stats-item .el-icon {
    color: var(--primary-color, #409eff);
  }

  .comment-list {
    min-height: 200px;
    background: var(--bg-color, #ffffff);
    border-radius: 12px;
    border: 1px solid var(--border-color, #e4e7ed);
    padding: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  }

  .no-comments {
    text-align: center;
    padding: 40px 20px;
    color: var(--text-secondary, #666);
  }

  .no-comments .el-empty {
    --el-empty-description-margin-top: 16px;
  }

  .load-more {
    text-align: center;
    margin-top: 20px;
    padding: 16px 0;
    border-top: 1px dashed var(--border-color, #e4e7ed);
  }

  .load-more .el-button {
    padding: 12px 32px;
    border-radius: 20px;
    font-weight: 500;
    transition: all 0.3s ease;
    background: var(--bg-secondary, #f8f9fa);
    border-color: var(--border-color, #e4e7ed);
    color: var(--text-primary, #303133);
  }

  .load-more .el-button:hover {
    background: var(--primary-color, #409eff);
    border-color: var(--primary-color, #409eff);
    color: white;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  }
</style>
